﻿using System;
using System.Text;
using System.IO;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web;
using Newtonsoft.Json;
using Api.Common;

namespace AppManager.Background
{
    /// <summary>
    /// 如果发生任何的异常，记录并跳转到~/Error/index页面
    /// </summary>
    public class CusExceptionFilter : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext exceptionContext)
        {
            var exception = exceptionContext.Exception;

            if (exception is System.Threading.Tasks.TaskCanceledException)
            {
                //不记录这种错误，没有意义
            }
            else if (exception is OperationCanceledException)
            {
                //不记录这种错误，没有意义
            }
            else if (exception is IOException)
            {
                //不记录这种错误，没有意义
            }
            else if (exception is NullReferenceException)
            {

            }
            else
            {
                exceptionContext.Result = new RedirectToRouteResult(new RouteValueDictionary()
                        {
                            { "area",""},
                            {"controller","Error"},
                            {"action","Index" },
                        });

                #region 记录日志
                var request = HttpContext.Current.Request;
                var stream = request.InputStream;
                byte[] param = HttpContext.Current.Request.BinaryRead(HttpContext.Current.Request.ContentLength);
                string strRequest = Encoding.ASCII.GetString(param);

                string exceptionStr = "";
                if (exception != null)
                {
                    exceptionStr = JsonConvert.SerializeObject(exception, Formatting.Indented);
                }

                ExceptionBody body = new ExceptionBody
                {
                    Url = request.Url.ToString(),
                    body = JsonConvert.SerializeObject(request.Form),
                    InputStream = strRequest,
                    Exception = exceptionStr
                };

                if (exception != null)
                {
                    LogHelper.WriteErrorLog(body.ToString());
                }
                else
                {
                    LogHelper.WriteErrorLog("发生一个未知错误");
                }
                #endregion
            }
        }
    }

    public class ExceptionBody
    {
        public string UrlReferrer { get; set; }
        public string Url { get; set; }
        public string body { get; set; }
        public string InputStream { get; set; }
        public string Exception { get; set; }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }
    }
}